/*
 * @Author: hongbin
 * @Date: 2021-11-13 14:43:19
 * @LastEditors: hongbin
 * @LastEditTime: 2021-11-20 18:25:35
 * @Description:展示数据的table
 */
import { FC, ReactElement, useCallback, useMemo, useState } from "react";
import { PayloadProps } from ".";
import styled from "styled-components";
import { ThemeText } from "../styled";
import {
  Button,
  Dialog,
  DialogContent,
  DialogTitle,
  Typography,
} from "@mui/material";
import { deleteDocument, updateDocument } from "../../api/mongo";
import { useDBinfo } from "../../context/DBInfoContext";
import { LoadingButton } from "@mui/lab";
import DataItem from "./DataItem";
import UpdateField from "./UpdateField";

interface IProps {
  payload: PayloadProps;
  collection: string;
  onDelete: (delId: string) => void;
  onUpdate: (updateId: string, newField: any) => void;
}

interface DialogProps {
  open: boolean;
  type: "" | "DELETE" | "EDIT";
  data?: { _id: string };
}

const ShowData: FC<IProps> = ({
  payload,
  collection,
  onDelete,
  onUpdate,
}): ReactElement => {
  const { id: clientId } = useDBinfo();
  const [dialog, setDialog] = useState<DialogProps>({ open: false, type: "" });
  const [dialogLoad, setDialogLoad] = useState(false);
  const params = useMemo(
    () => ({ type: "mongo" as "mongo", clientId, collection }),
    [clientId, collection]
  );

  const onClose = useCallback(() => {
    setDialog(prev => ({ ...prev, open: false }));
  }, []);

  const handleDelete = useCallback(_id => {
    setDialog({ open: true, type: "DELETE", data: { _id } });
  }, []);

  const onEdit = useCallback((data: any) => {
    setDialog({ open: true, type: "EDIT", data });
  }, []);

  const { open, type, data = { _id: "" } } = dialog;
  const documentId = data!._id;

  const updateRequest = async (changeField: any, removeField: []) => {
    console.log(changeField, removeField);
    const result = await updateDocument({
      ...params,
      changeField,
      removeField,
      documentId,
    });
    if (result.data) {
      onUpdate(documentId, changeField);
      onClose();
    }
  };

  const deleteRequest = async () => {
    const result = await deleteDocument({ ...params, documentId });
    console.log("del data:", result);
    if (result.data) {
      onDelete(documentId);
    }
  };

  const onSubmit = async () => {
    setDialogLoad(true);
    if (type === "DELETE") await deleteRequest();
    setDialogLoad(false);
    onClose();
  };

  return (
    <Wrap>
      {payload.fetching ? "加载中..." : ""}
      {payload.data
        ? payload.data.map((item: any) => (
            <DataItem
              key={item._id}
              onDelete={handleDelete}
              onEdit={onEdit}
              main={true}
              data={item}
            />
          ))
        : null}

      <Dialog open={open}>
        <DialogTitle>
          {type === "DELETE" ? "确定删除document" : "更新document"}
        </DialogTitle>
        {type === "EDIT" ? (
          <DialogContent style={{ minWidth: "35rem" }}>
            <Typography variant="caption">
              很遗憾web操作数据库太过繁琐,目前只支持基本类型操作
            </Typography>
            <UpdateField
              data={data as any}
              onCancel={onClose}
              onSubmit={updateRequest}
            />
          </DialogContent>
        ) : (
          <>
            <Button disabled={dialogLoad} onClick={onClose}>
              取消
            </Button>
            <LoadingButton loading={dialogLoad} onClick={onSubmit}>
              确定
            </LoadingButton>
          </>
        )}
      </Dialog>
    </Wrap>
  );
};

export default ShowData;

const Wrap = styled.div`
  flex: 1;
  overflow: scroll;
  ${ThemeText};
`;
